package ldh.im.fxgui.controller;

import javafx.animation.ScaleTransition;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Tooltip;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.util.Duration;
import ldh.im.ImConfig;
import ldh.im.dto.business.user.UserUpdateReq;
import ldh.im.fxbase.dao.ImUserDao;
import ldh.im.fxbase.emoji.Emoji;
import ldh.im.fxbase.emoji.EmojiOne;
import ldh.im.fxbase.data.event.EventBusFactory;
import ldh.im.fxbase.data.pojo.ImUser;
import ldh.im.fxbase.util.BeanFactory;
import ldh.im.fxbase.util.RpcUtil;
import ldh.im.fxbase.util.ThreadPoolUtil;
import ldh.im.fxbase.rpc.service.RpcMessageService;
import ldh.im.fxbase.util.ImCacheFactory;
import ldh.im.fxgui.util.UserHeadImageUtil;
import ldh.rpc.cache.CacheService;

import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * 选择用户图像
 */
public class UserHeaderImageController extends BaseController implements Initializable {

    @FXML private Pane rootPane;
    @FXML private ScrollPane imagesPane;
    @FXML private ImageView headImageView;
    @FXML private StageControlController stagePaneController;
    @FXML private Pane movablePane;

    public void setStage(Stage stage) {
        stagePaneController.setStage(stage);
    }
    private ImUserDao imUserDao = BeanFactory.getInstance().getBean(ImUserDao.class);
    private RpcMessageService rpcMessageService = RpcUtil.getRpcBootstrap().getRpcConfig().getClientBean(RpcMessageService.class);

    public Pane getMovablePane() {
        return movablePane;
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        stagePaneController.hideMax();

        FlowPane flowPane = new FlowPane(10, 10);

        flowPane.setPadding(new Insets(10));
        Map<String, List<Emoji>> map = EmojiOne.getInstance().getCategorizedEmojis(6);
        List<Emoji> emojis = map.get("people");
        emojis.forEach(emoji -> flowPane.getChildren().add(createEmojiNode(emoji)));

        imagesPane.setContent(flowPane);
    }

    private Node createEmojiNode(Emoji emoji) {
        ImageView imageView = new ImageView();
        imageView.setFitWidth(32);
        imageView.setFitHeight(32);
        imageView.setImage(UserHeadImageUtil.getHeadImage(emoji.getHex()));
        imageView.setUserData(emoji.getHex());

        Tooltip tooltip = new Tooltip(emoji.getShortname());
        Tooltip.install(imageView, tooltip);
        imageView.setCursor(Cursor.HAND);
        ScaleTransition st = new ScaleTransition(Duration.millis(90), imageView);

        imageView.setOnMouseEntered(e-> {
            //stackPane.setStyle("-fx-background-color: #a6a6a6; -fx-background-radius: 3;");
            imageView.setEffect(new DropShadow());
            st.setToX(1.2);
            st.setToY(1.2);
            st.playFromStart();
        });
        imageView.setOnMouseExited(e-> {
            //stackPane.setStyle("");
            imageView.setEffect(null);
            st.setToX(1.);
            st.setToY(1.);
            st.playFromStart();
        });
        imageView.setOnMouseClicked(e->{
            headImageView.setEffect(new DropShadow());
            headImageView.setImage(UserHeadImageUtil.getHeadImage(emoji.getHex()));
            headImageView.setUserData(emoji.getHex());
        });

        return imageView;
    }

    public void selectSuccess(ActionEvent actionEvent) {
        if (mainController == null) return;
        if (headImageView.getUserData() == null) return;
        String icon = headImageView.getUserData().toString();
        mainController.setHeadIcon(icon);

        ThreadPoolUtil.submit(()->{
            try {
                CacheService cacheService = RpcUtil.getRpcBootstrap().getRpcConfig().getCacheService();
                String userId = (String) cacheService.getCache(ImConfig.LOGIN_USER_ID);
                ImUser imUser = ImCacheFactory.getInstance().getUser(userId);
                imUser.setHeadImg(icon);
                imUser.setUpdateTime(new Date());
                imUserDao.updateUser(imUser);

                EventBusFactory.getInstance().post(imUser);

                UserUpdateReq userUpdateReq = new UserUpdateReq();
                userUpdateReq.setUserId(userId);
                userUpdateReq.setHeadImage(icon);
                String result = rpcMessageService.userUpdateInfo(userUpdateReq);
//                FxThreadUtil.runLater(()-> DialogUtil.alert("提示", "更新头像成功"));
                return result;
            } catch (Exception e) {
                e.printStackTrace();
//                FxThreadUtil.runLater(()-> DialogUtil.alert("提示", "更新头像失败"));
            }
            return null;
        });

    }

    public void exit(ActionEvent actionEvent) {
        if (mainController == null) return;

    }

}
